package oct2013.linkednode;

public class ReverseNodesinkGroup {
	public ListNode reverseKGroup(ListNode head, int k) {
		ListNode dummy = new ListNode(0);
		dummy.next = head;
		ListNode cur = head;
		ListNode prev = dummy;
		int i = 0;
		while (cur != null) {
			i++;
			if (i % k == 0) {
				ListNode tmp = prev.next;
				prev.next = reverse(prev.next, cur);
				prev = tmp;
				cur = tmp;
			}
			cur = cur.next;
		}
		return dummy.next;
	}

	ListNode reverse(ListNode from, ListNode to) {
		ListNode cur = from.next;
		from.next = to.next;
		while (from != to) {
			ListNode tmp = cur.next;
			cur.next = from;
			from = cur;
			cur = tmp;
		}
		return to;
	}
}
